package FileIO;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class DeleteFile {
    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要扫描的根目录：");
        String srcPath = scanner.next();

        File src = new File(srcPath);
        if (!src.isDirectory()) {
            System.out.println("输入目录不存在或有误，退出程序");
            return;
        }

        System.out.println("请输入文件中要查找的字符：");
        String token = scanner.next();
        List<File> fileList = new ArrayList<>();
        matchName(src, token, fileList);

        System.out.println("共找到"+fileList.size()+"份文件");
        for (File f : fileList) {
            System.out.println(f.getCanonicalPath()+"是否删除该文件？ y/n");
            String ans = scanner.next();
            if (ans.equalsIgnoreCase("y")) {
                f.delete();
                System.out.println("删除成功");
            }
        }
    }


    private static void matchName(File src, String token, List<File> fileList) {
        File[] files = src.listFiles();
        if (files == null) {
            return;
        }
        for (File f : files) {
            if (f.isDirectory()) {
                matchName(f, token, fileList);
            } else {
                if (f.getName().contains(token)) {
                    fileList.add(f.getAbsoluteFile());
                }
            }
        }
    }
}







